import { useTranslation } from 'react-i18next';
import moment from 'moment';
import {
  Grid,
  Typography,
  Box,
  useTheme
} from '@mui/material';

// Icons
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import WarningAmberIcon from '@mui/icons-material/WarningAmber';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import EventIcon from '@mui/icons-material/Event';
import AutorenewIcon from '@mui/icons-material/Autorenew';

// Styled Components
import {
  StyledPaper,
  StyledAppButton
} from 'components/objects/StyledComponents';

/**
 * UserInfo component that displays user details and subscription status
 * 
 * @param {Object} props
 * @param {Object} props.user - User object containing email and account data
 * @param {Object} props.subscription - Current subscription object
 * @param {Function} props.hasFailedPayment - Utility function to check for failed payments
 * @param {Function} props.onUpdatePayment - Optional handler for payment update button
 */
const UserInfo = ({
  user,
  subscription,
  hasFailedPayment,
  onUpdatePayment
}) => {
  const { t } = useTranslation();
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';

  // Format date from Unix timestamp
  const formatDate = (unixTimestamp) => {
    return moment.unix(unixTimestamp).format("DD/MM/YYYY");
  };

  // Format date from ISO string
  const formatISODate = (isoDate) => {
    return moment(isoDate).format("DD/MM/YYYY");
  };

  // Check for payment failures
  const hasPaymentFailed = hasFailedPayment(user.account);
  const isPastDue = subscription?.status === "past_due";

  // Status item component to show status with icon
  const StatusItem = ({ icon, text, action }) => (
    <Box
      sx={{ 
        display: 'flex', 
        alignItems: 'center',
        p: 1.5,
        mb: 1.5,
        borderRadius: 1,
        background: isDarkMode ? 'rgba(0, 0, 0, 0.2)' : 'rgba(255, 255, 255, 0.7)',
        boxShadow: isDarkMode 
          ? 'inset 1px 1px 2px rgba(0, 0, 0, 0.2), inset -1px -1px 2px rgba(255, 255, 255, 0.05)' 
          : 'inset 1px 1px 2px rgba(223, 227, 238, 0.5), inset -1px -1px 2px rgba(255, 255, 255, 0.7)'
      }}
    >
      <Box sx={{ mr: 1.5 }}>
        {icon}
      </Box>
      <Box sx={{ flex: 1 }}>
        {text}
      </Box>
      {action && (
        <Box sx={{ ml: 1 }}>
          {action}
        </Box>
      )}
    </Box>
  );

  return (
    <Grid item xs={12}>
      <StyledPaper darkMode={isDarkMode} sx={{ p: 3 }}>
        {/* User Email Header */}
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
          <AccountCircleIcon 
            color="primary" 
            sx={{ fontSize: 32, mr: 2 }}
          />
          <Typography variant="h5" component="h1">
            {user.email}
          </Typography>
        </Box>

        {/* Status Information */}
        <Box>
          {/* Failed Payment Warning */}
          {hasPaymentFailed && (
            <>
              <StatusItem 
                icon={<WarningAmberIcon color="error" sx={{ fontSize: 20 }} />}
                text={
                  <Typography color="error">
                    {t("dashboardPage.failedPaymentAt")}{" "}
                    {formatISODate(user.account.paymentFailedFirstAt)}
                  </Typography>
                }
              />
              <StatusItem 
                icon={<ErrorOutlineIcon color="error" sx={{ fontSize: 20 }} />}
                text={
                  <Typography color="error">
                    {t("dashboardPage.subscriptionDeactivateOn")}{" "}
                    {formatISODate(user.account.paymentFailedSubscriptionEndsAt)}
                  </Typography>
                }
              />
            </>
          )}

          {/* Subscription Status (if no payment failure) */}
          {!hasPaymentFailed && subscription && (
            <StatusItem 
              icon={
                subscription.canceled_at 
                  ? <EventIcon color="warning" sx={{ fontSize: 20 }} />
                  : <AutorenewIcon color="success" sx={{ fontSize: 20 }} />
              }
              text={
                <Typography color={subscription.canceled_at ? "warning.main" : "success.main"}>
                  {subscription.canceled_at 
                    ? t("dashboardPage.subscriptionDeactivateOn")
                    : t("dashboardPage.subscriptionRenewOn")
                  }{" "}
                  {formatDate(subscription.current_period_end)}
                </Typography>
              }
            />
          )}

          {/* Past Due Warning */}
          {isPastDue && (
            <StatusItem 
              icon={<WarningAmberIcon color="error" sx={{ fontSize: 20 }} />}
              text={
                <Typography color="error">
                  {t("dashboardPage.checkYourPayments")}
                </Typography>
              }
              action={
                <StyledAppButton 
                  darkMode={isDarkMode}
                  variant="outlined" 
                  color="error" 
                  size="small"
                  onClick={onUpdatePayment}
                  sx={{ py: 0.5 }}
                >
                  {t("dashboardPage.updatePayment")}
                </StyledAppButton>
              }
            />
          )}
        </Box>
      </StyledPaper>
    </Grid>
  );
};

export default UserInfo;